/**
 * <p><b>Title:</b> DefaultPrdSalManager.java </p>
 *
 * @Package com.wondertek.oes.charge.service.manager
 */
package com.wondertek.poms.core.manager;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.wondertek.poms.common.constant.Constants;
import com.wondertek.poms.common.utils.StringUtil;
import com.wondertek.poms.core.filter.RuleFilterChain;
import com.wondertek.poms.core.filter.impl.AssertLevelFilter;
import com.wondertek.poms.core.filter.impl.CopyRightTypeFilter;
import com.wondertek.poms.core.filter.impl.FirClassifyFilter;
import com.wondertek.poms.core.filter.impl.FirstPulishFilter;
import com.wondertek.poms.core.filter.impl.FormTypeFilter;
import com.wondertek.poms.core.filter.impl.FreeTypeFilter;
import com.wondertek.poms.core.filter.impl.KeyWordFilter;
import com.wondertek.poms.core.filter.impl.SecondClassifyFilter;
import com.wondertek.poms.core.service.IDefaultPrdSalService;
import com.wondertek.poms.core.service.IEquityNodeService;
import com.wondertek.poms.core.service.IMamRecommendService;
import com.wondertek.poms.core.service.ISellingPriceService;
import com.wondertek.poms.core.service.ISellingPriceTagService;
import com.wondertek.poms.core.utils.OutHttpUtil;
import com.wondertek.poms.dao.po.Content;
import com.wondertek.poms.dao.po.DefaultPrdSal;
import com.wondertek.poms.dao.po.EquityNode;
import com.wondertek.poms.dao.po.MamRecommend;
import com.wondertek.poms.dao.po.PrdCont;
import com.wondertek.poms.dao.po.PrdInfo;
import com.wondertek.poms.dao.po.SellingPrice;
import com.wondertek.poms.dao.po.SellingPriceTag;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * <b>DefaultPrdSalManager Description:</b> 批价组件
 * </p>
 *
 * @author douzi <b>DATE</b> 2019年3月1日 上午10:15:57
 */
@Slf4j
@Component
public class ChargeManager {
	@Autowired
	private IDefaultPrdSalService defaultPrdSalService;
    @Autowired
    private ISellingPriceService sellingPriceVoucherService;
    @Autowired
    private ISellingPriceTagService sellingPriceCouponsService;
    @Autowired
    private IMamRecommendService mamRecommendService;
    @Autowired
    private IEquityNodeService equityNodeService;
    @Resource
    private OutHttpUtil outHttpUtil;

    /**
     * <p><b>Title:</b> setParentEquityId</p>
     * <p><b>Description:</b> 直播节目单没有推荐标签时，使用所属直播频道权益</p>
     *
     * @param prdCont
     * @param parentPrdCont
     * @author douzi
     */
    public void setParentEquityId(PrdCont prdCont, PrdCont parentPrdCont) {
        prdCont.setEquityId(parentPrdCont.getEquityId());
    }

    /**
     * <p><b>Title:</b> matchEquityId</p>
     * <p><b>Description:</b> 匹配权益</p>
     *
     * @param prdInfo
     * @param vo
     * @author douzi
     */
    public void matchEquityId(PrdCont prdCont, PrdInfo prdInfo, Content c) {
        String equityIdSwitch = outHttpUtil.findByKey("AUTO_EQUITY_ID_SWITCH");//配置开关
        String isAutoPrdInfo = outHttpUtil.findByKey("AUTO_EQUITY_ID_PRDINFO");//配置商品包
        StringBuffer allEquityId = new StringBuffer();
        if ("on".equals(StringUtils.lowerCase(equityIdSwitch))) {
            if (StringUtils.isNotBlank(isAutoPrdInfo) && isAutoPrdInfo.contains(prdInfo.getPrdInfoId() + "")) {
                String mamRecommend = c.getRecommendation();//获取内容上的推荐标签（正常不为空）
                if (StringUtils.isBlank(mamRecommend)) {
                    log.info("主流程|权益|自动匹配权益节点|AssetId:" + c.getAssetId() + "|内容id:" + c.getContentId() + "|内容推荐标签为空 ");
                    return;
                }
                String[] contentMamRecommend = mamRecommend.split(",");
                for (String recommend : contentMamRecommend) {
                	MamRecommend enr = new MamRecommend();
                    enr.setMamRecommend(recommend);
                    List<MamRecommend> enrs = mamRecommendService.findAll(enr);
                    if (enrs != null && enrs.size() > 0) {
                    	MamRecommend temp = enrs.get(0);
                        String equityName = temp.getEquityId();

                        EquityNode params = new EquityNode();
                        params.setName(equityName);

                        List<EquityNode> ens = equityNodeService.findAll(params);
                        if (ens != null && ens.size() > 0) {
                            EquityNode equityNode = ens.get(0);
                            allEquityId.append(equityNode.getId() + ",");
                        }
                    }
                }
                String ei = allEquityId.length() > 0 ? allEquityId.toString().substring(0, allEquityId.length() - 1) : "";

                if (StringUtils.isNotBlank(ei)) {
                    prdCont.setEquityId(ei);
                }
            }
        }

        log.info("主流程|权益结果|权益值为:" + prdCont.getEquityId() + "|内容id:" + c.getContentId() +  "|AssetId:" + c.getAssetId());
    }

    /**
     * <p><b>Title:</b> chargePrdCont</p>
     * <p><b>Description:</b> 批价</p>
     *
     * @param prdInfo
     * @param vo
     * @author douzi
     */
    public void chargePrdCont(PrdCont prdCont, PrdInfo prdInfo, Content c) {
        setDefaultAutoCharge(prdCont, prdInfo, c);

        //配置显示产品编号的包
        Long prdInfoId = prdInfo.getPrdInfoId();
        setDisplayPrdInfo(prdCont, prdInfoId);

        boolean isPersonOperationFlag = isPersonOperation(prdCont);

        boolean configPrice = getSellingPricePrdInfo(prdInfoId);

        setVoucher(prdCont, c, isPersonOperationFlag, configPrice, prdInfo);

        boolean isUserDefined = getUserDefined(prdInfoId);

        setCoupons(prdCont, prdInfo, c, isPersonOperationFlag, isUserDefined);

        log.info("主流程|批价结果|产品编号为:" + prdCont.getProductId() + "|内容id:" + c.getContentId() + "|AssetId:" + c.getAssetId() + "|售价名称计费setSellingPrice:" + prdCont.getSellingPrice());
    }

    /**
     * <p><b>Title:</b> setCoupons</p>
     * <p><b>Description:</b> 设置观赛券批价，老的用户自定义批价</p>
     *
     * @param prdCont               节目
     * @param prdInfo               商品包
     * @param vo                    媒资
     * @param isPersonOperationFlag 人工标志
     * @param isUserDefined         人工标志
     * @author douzi
     */
    private void setCoupons(PrdCont prdCont, PrdInfo prdInfo, Content c, boolean isPersonOperationFlag,
                            boolean isUserDefined) {
        if (isUserDefined && !isPersonOperationFlag) {
            String[] mamRecommends = null;
            String productIds = "";
            // 售价从自定义售价表中获取
            if (StringUtils.isNotBlank(c.getRecommendation())) {
                mamRecommends = c.getRecommendation().replaceAll("，", ",").split(",");
            }
            if (mamRecommends == null || mamRecommends.length <= 0) {
                SellingPriceTag defalutTag = sellingPriceCouponsService.findDefaultPrice(prdInfo.getPrdInfoId());
                productIds = "," + defalutTag.getProductId();
            } else {
            	productIds = matchRecommend(prdInfo, mamRecommends);
            }
            log.info("主流程|批价观赛券|媒资ID:" + c.getAssetId() + "|内容id:" + c.getContentId() + 
            		"|入包二级产品:" + prdInfo.getProductInfoPackageId() + "|产品IDs:" + productIds + 
            		"|mamRecommends:" + mamRecommends);
            setSellingPriceOrProductId(prdCont, productIds);
        }
    }

    /**
     * <p><b>Title:</b> getDefaultCoupons</p>
     * <p><b>Description:</b> 观赛券:获取默认产品id</p>
     *
     * @param prdInfo
     * @param productIds
     * @return
     * @author douzi
     */
    private String getDefaultCoupons(PrdInfo prdInfo, String productIds) {
        if (StringUtils.isBlank(productIds)) {
            SellingPriceTag pspc = sellingPriceCouponsService.findDefaultPrice(prdInfo.getPrdInfoId());
            if (pspc != null) {
                Long productId = pspc.getProductId();
                log.info("主流程|批价观赛券|自定义售价商品包的默认售价产品Id:" + productId.toString());
                if (productId != null) {
                    productIds = productIds + "," + productId;
                }
            } else {
                log.error("主流程|批价观赛券|自定义售价商品包:" + prdInfo.getPrdInfoId() + "|默认售价未配置 ");
            }
        }
        return productIds;
    }

    /**
     * <p><b>Title:</b> matchRecommend</p>
     * <p><b>Description:</b> 观赛券: 匹配推荐标签获取对应产品id</p>
     *
     * @param prdInfo
     * @param mamRecommends
     * @return
     * @author douzi
     */
    private String matchRecommend(PrdInfo prdInfo, String[] mamRecommends) {
        boolean defaultFlag = true;
        StringBuilder productIds = new StringBuilder();
        for (String mamRecommend : mamRecommends) {
            if (StringUtils.isNotBlank(mamRecommend)) {
            	SellingPriceTag spc = new SellingPriceTag();
                spc.setPrdInfoId(prdInfo.getPrdInfoId() + "");
                spc.setMamRecomend(mamRecommend);
                SellingPriceTag pspc = sellingPriceCouponsService.findOne(spc);
                if (pspc != null) {
                    defaultFlag = false;
                    Long productId = pspc.getProductId();
                    log.info("主流程|批价观赛券|匹配推荐标签对应产品Id:" + productId.toString());
                    productIds.append(",").append(productId);
                }
            }
        }

        String temp = productIds.toString();
        if (defaultFlag) {
            temp = getDefaultCoupons(prdInfo, temp);
        }
        return temp;
    }

    /**
     * <p><b>Title:</b> getUserDefined</p>
     * <p><b>Description:</b> 获取用户自定义标记</p>
     *
     * @param prdInfoId
     * @return
     * @author douzi
     */
    private boolean getUserDefined(Long prdInfoId) {
        // 对特定产品包自定义售价的包
        // 功能优化，咪咕视频PP收费包中，推荐标签中包含中超等信息的节目，可自定义节目售价。
        boolean isUserDefined = false;
        String userDefinedPrice = outHttpUtil.findByKey("SELLING_PRICE_TAG_PRDINFO");
        log.info("主流程|批价|商品包:" + prdInfoId + "|根据媒资标签定售价的产品包:" + userDefinedPrice);
        if (StringUtils.isNotBlank(userDefinedPrice)) {
            if (userDefinedPrice.indexOf(prdInfoId + "") >= 0) {
                isUserDefined = true;
            }
        }
        return isUserDefined;
    }

    /**
     * <p><b>Title:</b> setVoucher</p>
     * <p><b>Description:</b> 设置观影券批价，老的售价等于定价 </p>
     *
     * @param prdCont
     * @param vo
     * @param isPersonOperationFlag
     * @param configPrice
     * @author douzi
     */
    private void setVoucher(PrdCont prdCont, Content c, boolean isPersonOperationFlag, boolean configPrice, PrdInfo prdInfo) {
        //售价等于定价
        if (configPrice && !isPersonOperationFlag) {
            String productIds = "";
            String pricing = c.getPricing();
//			String unitPricing = vo.getUnitPricing();
//			String monthPricing = vo.getMonthPricing();
            try {
                if (StringUtils.isNotBlank(pricing)) {
                    productIds = addSellingPrice(productIds, pricing);
                }
//				if (StringUtils.isNotBlank(unitPricing)) {
//					productIds = addSellingPrice(productIds, unitPricing);
//				}
//				if (StringUtils.isNotBlank(monthPricing)) {
//					productIds = addSellingPrice(productIds, monthPricing);
//				}

                log.info("主流程|批价观影券|媒资ID:" + c.getAssetId() + "|内容id:" + c.getContentId() + 
                		"|入包二级产品:" + prdInfo.getProductInfoPackageId() + "|商品包id：" + prdInfo.getPrdInfoId() + 
                		"|定价:" + pricing + "|产品IDs:" + productIds);
                setSellingPriceOrProductId(prdCont, productIds);
            } catch (Exception e) {
                log.info(e.getMessage());
            }
        }
    }

    /**
     * <p><b>Title:</b> setSellingPriceOrProductId</p>
     * <p><b>Description:</b> 观影券or观赛券:设置所有基本计费或者售价名称计费 </p>
     *
     * @param prdCont
     * @param productIds
     * @author douzi
     */
    private void setSellingPriceOrProductId(PrdCont prdCont, String productIds) {
        if (StringUtils.isNotBlank(productIds) && productIds.length() > 0) {
            String productId = productIds.substring(1).split(",")[0];

            log.info("主流程|批价|商品包:" + prdCont.getPrdInfoId() + "|内容id:" + prdCont.getContentId() + "|设置前:" + prdCont.getProductId());
            if (StringUtils.isBlank(prdCont.getProductId())) {
                prdCont.setProductId(productId);
            } else {
                String prdProductId = prdCont.getProductId();
                
//                if (prdCont.getSellingPrice() != null && !"".equals(prdCont.getSellingPrice())) {
////                    prdProductId = prdProductId.replace(prdCont.getSellingPrice(), productId + "");
//                    prdCont.setProductId(prdProductId + "," + productId);
//                } else {
//                    prdCont.setProductId(prdCont.getProductId() + "," + productId);
//                }
                
                if (("," + prdProductId + ",").indexOf("," + productId + ",") < 0) {
                	prdCont.setProductId(prdProductId + "," + productId);
            	}
                log.info("主流程|批价|商品包:" + prdCont.getPrdInfoId() + "|内容id:" + prdCont.getContentId() + 
                		"|基本计费或者售价名称计费结果:" + prdCont.getProductId() + "|条件比较:," + prdProductId + ",|," + productId + ",");
            }
            prdCont.setSellingPrice(productId + "");
        }
    }

    /**
     * <p><b>Title:</b> addSellingPrice</p>
     * <p><b>Description:</b> 观影券:根据媒资定价添加自动计费</p>
     *
     * @param productIds
     * @param pricing
     * @return
     * @author douzi
     */
    private String addSellingPrice(String productIds, String pricing) {
    	SellingPrice spv = new SellingPrice();
        spv.setSellingPriceNum(StringUtil.nullToLong(pricing));
        SellingPrice spvOpt = sellingPriceVoucherService.findOne(spv);
        if (spvOpt != null) {
            productIds = productIds + "," + spvOpt.getProductId();
        }
        return productIds;
    }

    /**
     * <p><b>Title:</b> getSellingPricePrdInfo</p>
     * <p><b>Description:</b> 判断是否是售价等于定价的包</p>
     *
     * @param prdInfoId
     * @return
     * @author douzi
     */
    private boolean getSellingPricePrdInfo(Long prdInfoId) {
        String prdInfos = outHttpUtil.findByKey("SELLING_PRICE_PRDINFO");
        boolean configPrice = false;
        if (StringUtils.isNotBlank(prdInfos)) {
            if (prdInfos.indexOf(prdInfoId + "") >= 0) {
                configPrice = true;
            }
        }
        log.info("主流程|批价|商品包:" + prdInfoId + "|是否是售价等于定价的包:" + configPrice);

        return configPrice;
    }

    /**
     * <p><b>Title:</b> isPersonOperation</p>
     * <p><b>Description:</b> 判断运维人员是否操作过</p>
     *
     * @param prdCont
     * @return
     * @author douzi
     */
    private boolean isPersonOperation(PrdCont prdCont) {
        String isPersonOperation = prdCont.getIsPersonOperation();
        log.info("主流程|批价|媒资ID:" + prdCont.getMmsId() + "|内容id:" + prdCont.getContentId() + "|运维人员是否操作过:" + isPersonOperation);
        // 售价名称计费是否人工添加  1.是
        return Constants.YES_1.equals(isPersonOperation);
    }

    /**
     * <p><b>Title:</b> isDisplayPrdInfo</p>
     * <p><b>Description:</b> 发布的xml中是否显示productId  </p>
     *
     * @param prdCont
     * @param prdInfoId
     * @author douzi
     */
    private void setDisplayPrdInfo(PrdCont prdCont, Long prdInfoId) {
        String notShowId = outHttpUtil.findByKey("PRDINFO_NOT_SHOW_PRODUCTID");
        if (StringUtils.isNotBlank(notShowId)) {
            if (notShowId.indexOf(prdInfoId + "") > 0) {
                // IsShowPrdId 1:是 ，0 否
                prdCont.setIsShowPrdId(Constants.NO_0);
            }
        }
        log.info("主流程|批价|商品包id:" + prdInfoId + "|内容id:" + prdCont.getContentId() + "|notShowId:" + notShowId);
    }

    /**
     * <p><b>Title:</b> setDefaultAutoCharge</p>
     * <p><b>Description:</b> 主流程自动设置默认计费</p>
     *
     * @param prdCont
     * @param prdInfo
     * @param vo
     * @author douzi
     */
    private void setDefaultAutoCharge(PrdCont prdCont, PrdInfo prdInfo, Content c) {
        log.info("主流程|批价-自动设置默认计费|媒资ID:" + c.getAssetId() + "|内容id:" + c.getContentId() + "|入包二级产品:" + prdInfo.getProductInfoPackageId() + "|商品包id:"
                + prdInfo.getPrdInfoId());
        DefaultPrdSal params = new DefaultPrdSal();
        params.setPrdInfoId(prdInfo.getPrdInfoId() + "");
        List<DefaultPrdSal> pirs = defaultPrdSalService.findAll(params);
        if (null != pirs && pirs.size() > 0) {
          for (DefaultPrdSal r : pirs) {
              if (this.filterCont(r, c)) {
                  long chargePointId = Long.parseLong(r.getProductId());
                  prdCont.setProductId(chargePointId + "");
                  prdCont.setSellingPrice("");
                  prdCont.setPrice(r.getPrice());
                  prdCont.setOrderFlag(r.getOrderFlag() + "");
                  break;
              }
          }
      }
    }

    /**
     * <p><b>Title:</b> filterCont</p>
     * <p><b>Description:</b> 过滤媒资，判断是否符合默认计费规则</p>
     *
     * @param r
     * @param vo
     * @return
     * @author douzi
     */
    private boolean filterCont(DefaultPrdSal r, Content vo) {
        RuleFilterChain rfc = new RuleFilterChain();
        rfc.addFilter(new FirClassifyFilter())  	// 一级分类
	        .addFilter(new AssertLevelFilter()) 	// 内容评级
	        .addFilter(new FormTypeFilter())    	// 剧集类型
	        .addFilter(new FreeTypeFilter())    	// 是否收费
	        .addFilter(new FirstPulishFilter())  	// 是否首发
	        .addFilter(new CopyRightTypeFilter()) 	// 版权类型
	        .addFilter(new SecondClassifyFilter()) 	// 二级分类
	        .addFilter(new KeyWordFilter())        	// 关键字
            .doFilter( r, vo, rfc);

        if (rfc.isFlag()) {
            log.info("assetId:" + vo.getAssetId() + "|内容id:" + vo.getContentId() + "|商品包默认计费|" + r.toString());
        } else {
            log.warn("assetId:" + vo.getAssetId() + "|内容id:" + vo.getContentId() + "|商品包默认计费|" + rfc.getResultStr().toString());
        }
        return rfc.isFlag();
    }
}
